package com.yuner.search.controller;

import com.yuner.search.config.ElasticSearchConfig;
import com.yuner.search.repository.PhoneRepository;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @author Seven-Liu
 * @date 2022-07-03
 */
@RestController
@RequestMapping(value = "/search")
public class SearchController {

//    @Autowired
//    private PhoneRepository phoneRepository;
    @Autowired
    private ElasticSearchConfig elasticSearchConfig;

    @RequestMapping(value = "/getIndex", method = RequestMethod.GET)
    public SearchResponse getIndex() throws IOException {

        RestHighLevelClient esClient = elasticSearchConfig.elasticsearchClient();

        SearchRequest request = new SearchRequest();
        request.indices("yuner");
        request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));

        SearchResponse search = esClient.search(request, RequestOptions.DEFAULT);

        System.out.println(search);
        esClient.close();
        return search;
    }

    @RequestMapping(value = "/putIndex", method = RequestMethod.PUT)
    public SearchResponse putIndex() throws IOException {

        RestHighLevelClient esClient = elasticSearchConfig.elasticsearchClient();

        SearchRequest request = new SearchRequest();
        request.indices("yuner");
        request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));

        SearchResponse search = esClient.search(request, RequestOptions.DEFAULT);

        System.out.println(search);
        esClient.close();
        return search;
    }


}
